package com.jhy.product.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jhy.product.entity.CategoryEntity;
import com.jhy.product.service.CategoryService;
import com.jhy.common.utils.PageUtils;
import com.jhy.common.utils.R;



/**
 * 商品三级分类
 *
 * @author jhy
 * @email 2496085873@qq.com
 * @date 2021-05-09 11:02:17
 */
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 查询商品所有分类以及子分类，以树形结构组装起来
     */
    @RequestMapping("/list/tree")
    public R list(){
        List<CategoryEntity> entitiesWithTree = categoryService.listWithTree();//实现逻辑放在categoryServiceImpl
        return R.ok().put("entitiesWithTree", entitiesWithTree);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{catId}")
    //@RequiresPermissions("product:category:info")
    public R info(@PathVariable("catId") Long catId){
		CategoryEntity category = categoryService.getById(catId);

        return R.ok().put("categoryById", category);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("product:category:save")
    public R save(@RequestBody CategoryEntity category){
		categoryService.save(category);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("product:category:update")
    public R update(@RequestBody CategoryEntity category){
		categoryService.updateById(category);

        return R.ok();
    }

    /*
    批量修改
     */
    @RequestMapping("/update/sort")
    public R updateSort(@RequestBody CategoryEntity[] categories){
        categoryService.updateBatchById(Arrays.asList(categories));
        return R.ok();
    }

    /**
     * 删除
     * @RequestBody:获取请求体，SpringMVC自动将请求体中的数据(json)，转化为对应的对象
     * 只有Post请求才有请求体，所以前端必须发送post请求
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] catIds){
        //删除之前需要判断待删除的菜单是否被别的地方引用

        categoryService.removeMenuByIds(Arrays.asList(catIds));
        return R.ok();
    }

    /*
    批量删除
     */
    @RequestMapping("/batchDelete")
    public R batchDelete(@RequestBody CategoryEntity[] categories){
        //删除之前需要判断待删除的菜单是否被别的地方引用
        ArrayList<Long> list = new ArrayList<>();
        for(CategoryEntity categoryEntity : categories){
            list.add(categoryEntity.getCatId());
        }
        categoryService.removeByIds(list);
        return R.ok();
    }

}
